package controller

import (
	"fmt"
	"myblogs/Lib"
	"myblogs/app/variable"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

type ArticleController struct {
	*BaseController
}

// var (
// 	articleModel  *article.ArticleModel
// 	categoryModel *category.CategoryModel
// 	tagModel      *tag.TagModel
// )
//
// func init() {
// 	articleModel = new(article.ArticleModel)
// 	categoryModel = new(category.CategoryModel)
// 	tagModel = new(tag.TagModel)
// }

func (a *ArticleController) GetArticleList(c *gin.Context) {
	articles := articleModel.GetArticleList()
	for _, a := range articles {
		a.CreatedTimeStr = a.CreatedTime.Format("2006-01-02")

		cover := a.Cover
		if len(cover) == 0 {
			categoryInfo := categoryModel.GetCategoryInfo(a.CategoryId)
			a.Cover = categoryInfo.Cover
		}

		a.Cover = variable.ImgHost + a.Cover

		enId, _ := Lib.EnPwdCode([]byte(strconv.FormatInt(a.Id, 10)))
		a.ArticleId = enId
	}

	articleLatest := articleModel.GetArticleLatest()
	articleTotal := articleModel.GetArticleTotal()
	categoryTotal := categoryModel.GetCategoryTotal()
	tags := tagModel.GetTagAll(10)

	data := gin.H{
		"articles":      articles,
		"articleLatest": articleLatest,
		"articleTotal":  articleTotal,
		"categoryTotal": categoryTotal,
		"tags":          tags,
		"title":         "文章列表_全栈工匠",
		"keywords":      "全栈开发，系统架构，后端博客，前端博客，后端框架，前端框架，PHP，Java，C#，Golang，Python，Vue，Html，Javascript，CSS",
		"description":   "一个专注于分享全栈以及系统架构技术和趋势的博客",
		"site":          "zhongxc.cc",
	}
	// 渲染模板
	c.HTML(http.StatusOK, "archives.tmpl", data)
}

func (a *ArticleController) GetArticleInfo(c *gin.Context) {
	id := c.Param("id")
	// aid, _ := Lib.DePwdCode(id)
	idArr := strings.Split(id, ".")
	articleId, _ := strconv.ParseInt(idArr[0], 10, 64)
	articleInfo := articleModel.GetArticleInfo(articleId)
	articleInfo.CreatedTimeStr = articleInfo.CreatedTime.Format("2006-01-02")
	articleInfo.CreatedTimeStr2 = articleInfo.CreatedTime.Format("01/02")
	articleInfo.ArticleId = idArr[0]

	// decodeString, _ := base64.URLEncoding.DecodeString(id)
	// fmt.Printf("%s", decodeString)

	articleLatest := articleModel.GetArticleLatest()
	articleTotal := articleModel.GetArticleTotal()
	categoryTotal := categoryModel.GetCategoryTotal()
	tags := tagModel.GetTagAll(10)
	clickCount := articleModel.GetClickCountById(articleId)
	likeCount := articleModel.GetLikeCountById(articleId)

	articleInfo.LikeCount = likeCount

	data := gin.H{
		"articleInfo":   articleInfo,
		"articleLatest": articleLatest,
		"articleTotal":  articleTotal,
		"categoryTotal": categoryTotal,
		"tags":          tags,
		"tagList":       strings.Split(articleInfo.Tags, ","),
		"title":         articleInfo.Title + "_全栈工匠",
		"keywords":      articleInfo.Title,
		"description":   articleInfo.Summary,
		"site":          "zhongxc.cc",
		"pvCount":       a.GetPv(),
		"likeCount":     articleModel.GetLikeCount(),
		"clickCount":    clickCount,
	}
	c.HTML(http.StatusOK, "detail.tmpl", data)
}

func (a *ArticleController) ClickLike(c *gin.Context) {
	id := c.Param("id")
	// aid, _ := Lib.DePwdCode(id)
	articleId, _ := strconv.ParseInt(id, 10, 64)

	_ = articleModel.ClickLike(articleId)

	c.JSON(http.StatusOK, gin.H{})
}

// GetArticleListIndex 文章列表页面
func (a *ArticleController) GetArticleListIndex(c *gin.Context) {
	pageResult := a.ArticlePageList("", 1)

	pageResult["title"] = "文章列表_全栈工匠"
	pageResult["keywords"] = "全栈开发，系统架构，后端博客，前端博客，后端框架，前端框架，PHP，Java，C#，Golang，Python，Vue，Html，Javascript，CSS"
	pageResult["description"] = "一个专注于分享全栈以及系统架构技术和趋势的博客"
	pageResult["site"] = "zhongxc.cc"
	pageResult["pvCount"] = a.GetPv()
	pageResult["likeCount"] = articleModel.GetLikeCount()

	// 渲染模板
	c.HTML(http.StatusOK, "archives.tmpl", pageResult)
}

func (a *ArticleController) GetArticlePageList(c *gin.Context) {
	p := c.Param("page")
	page, _ := strconv.ParseInt(p, 20, 64)
	pageResult := a.ArticlePageList("", page)
	pageResult["pvCount"] = a.GetPv()
	pageResult["likeCount"] = articleModel.GetLikeCount()
	pageResult["title"] = "文章列表_全栈工匠"

	// 渲染模板
	c.HTML(http.StatusOK, "archives.tmpl", pageResult)
}

func (a *ArticleController) ArticlePageList(keyword string, page int64) map[string]interface{} {
	pageResult := articleModel.GetArticlePage(page, 20, keyword, "", "", "")
	pageResult["keyword"] = keyword

	pageCount := pageResult["pageCount"]
	pc, err := strconv.ParseInt(fmt.Sprintf("%v", pageCount), 10, 64)
	if err != nil {
		fmt.Printf("%d\n", pc)
	}
	var pageHtml []map[string]string
	for i := 0; i < int(pc); i++ {
		if len(pageHtml) >= 5 {
			break
		}
		pageIndex := fmt.Sprintf("%d", i+1)
		ph := map[string]string{
			"url":       fmt.Sprintf("/archives/page/%s", pageIndex),
			"pageIndex": pageIndex,
		}
		pageHtml = append(pageHtml, ph)
	}

	pageResult["pageHtml"] = pageHtml

	// 下一分页
	nextPage := page + 1
	if page == pc {
		pageResult["nextPage"] = page
		pageResult["nextPageUrl"] = fmt.Sprintf("/archives/page=%d", page)
	} else {
		pageResult["nextPage"] = nextPage
		pageResult["nextPageUrl"] = fmt.Sprintf("/archives/page/%d", nextPage)
	}

	if page > 1 {
		pageResult["prevPage"] = page - 1
		if page-1 == 1 {
			pageResult["prevPageUrl"] = "/archives"
		} else {
			pageResult["prevPageUrl"] = fmt.Sprintf("/archives/page/%d", page-1)
		}
	} else {
		pageResult["prevPage"] = page
		pageResult["prevPageUrl"] = fmt.Sprintf("/archives/page/%d", page)
	}

	articleLatest := articleModel.GetArticleLatest()
	articleTotal := articleModel.GetArticleTotal()
	categoryTotal := categoryModel.GetCategoryTotal()
	tags := tagModel.GetTagAll(10)
	categorys := categoryModel.GetCategoryAll()
	articleCategoryMp := articleModel.GetArticleCategoryTotal()
	for _, category := range categorys {
		for _, mp := range articleCategoryMp {
			cid := mp["categoryId"]
			if category.Id == cid {
				category.Total = mp["total"]
			}
		}
	}

	pageResult["articleLatest"] = articleLatest
	pageResult["articleTotal"] = articleTotal
	pageResult["categoryTotal"] = categoryTotal
	pageResult["tags"] = tags
	pageResult["categorys"] = categorys

	return pageResult
}

func (a *ArticleController) GetArticleByCategory(c *gin.Context) {
	name := c.Param("name")
	keyword := c.DefaultQuery("keyword", "")
	p := c.DefaultQuery("page", "1")

	page, _ := strconv.ParseInt(p, 10, 64)

	pageResult := articleModel.GetArticlePage(page, 10, "", "", name, "")
	pageResult["keyword"] = ""
	pageResult["tag"] = name

	pageCount := pageResult["pageCount"]
	pc, err := strconv.ParseInt(fmt.Sprintf("%v", pageCount), 10, 64)
	if err != nil {
		fmt.Printf("%d\n", pc)
	}
	var pageHtml []map[string]string
	for i := 0; i < int(pc); i++ {
		if len(pageHtml) >= 5 {
			break
		}
		pageIndex := fmt.Sprintf("%d", i+1)
		ph := map[string]string{
			"url":       "/search?keyword=" + keyword + "&page=" + pageIndex,
			"pageIndex": pageIndex,
		}
		pageHtml = append(pageHtml, ph)
	}

	pageResult["pageHtml"] = pageHtml

	// 下一分页
	nextPage := page + 1
	if page == pc {
		pageResult["nextPage"] = page
		pageResult["nextPageUrl"] = fmt.Sprintf("/tags/%s?page=%d", keyword, page)
	} else {
		pageResult["nextPage"] = nextPage
		pageResult["nextPageUrl"] = fmt.Sprintf("/tags/%s?page=%d", keyword, nextPage)

	}

	if page > 1 {
		pageResult["prevPage"] = page - 1
		pageResult["prevPageUrl"] = fmt.Sprintf("/tags/%s?page=%d", keyword, page-1)
	} else {
		pageResult["prevPage"] = page
		pageResult["prevPageUrl"] = fmt.Sprintf("/tags/%s?page=%d", keyword, page)
	}

	pageResult["title"] = "全栈工匠-" + keyword
	pageResult["keywords"] = "全栈开发，系统架构，后端博客，前端博客，后端框架，前端框架，PHP，Java，C#，Golang，Python，Vue，Html，Javascript，CSS"
	pageResult["description"] = "一个专注于分享全栈以及系统架构技术和趋势的博客"
	pageResult["site"] = "zhongxc.cc"
	pageResult["pvCount"] = a.GetPv()
	pageResult["likeCount"] = articleModel.GetLikeCount()

	// 渲染模板
	c.HTML(http.StatusOK, "search.tmpl", pageResult)
}
